package syncagenttester;

import syncagent.SyncAgentService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.EventAdmin;
import org.osgi.util.tracker.ServiceTracker;

public class Activator implements BundleActivator {
	private ServiceTracker helloWorldTracker;
	private SyncAgentService helloService;
	//private OsgiServiceBinder binder;
	private EventPublisher eventPublisher = new EventPublisher();  
	
	public EventPublisher getEventPublisher() {  
		return eventPublisher;  
	}

	public void setService(SyncAgentService helloService) {
		this.helloService = helloService;
	}

	public void removeService() {
		this.helloService = null;
	}

	public void start(BundleContext context) throws Exception {
		//helloWorldTracker = new ServiceTracker(context, SyncAgentService.class.getName(), null);
		//helloWorldTracker.open();
		SyncAgentService hello;// = (SyncAgentService) helloWorldTracker.getService();
		System.out.println("search for service reference");
		ServiceReference refs = context.getServiceReference(SyncAgentService.class.getName());

		if (refs == null) {
			System.out.println("Hello service unavailable on HelloConsumer start");
		} 
		else {
			hello = (SyncAgentService) context.getService(refs);

			System.out.println(hello.sayHello());
		}
		
		// Event publishing
		/// OsgiServiceBinder is a utility class that binds OSGi Services  
        /// to properties using setter methods. We will use it here to  
		/// bind the EventAdmin to the EventPublisher.  
		
		refs = context.getServiceReference(EventAdmin.class.getName());

		if (refs == null) {
			System.out.println("EventAdmin unavailable on HelloConsumer start");
		} 
		else {
			EventAdmin eventAdm = (EventAdmin) context.getService(refs);
			eventPublisher.setEventAdmin(eventAdm);
			eventPublisher.publish();
		}
		/*
		binder = new OsgiServiceBinder(context);  
		binder.bind(getEventPublisher(), "setEventAdmin", 
				ServiceFilter.forInterface(EventAdmin.class.getName()));  
		getEventPublisher().start(); 
		*/ 
	}

	public void stop(BundleContext context) {
		ServiceReference refs = context.getServiceReference(SyncAgentService.class.getName());

		SyncAgentService hello = (SyncAgentService) context.getService(refs);
		if (hello == null) {
			System.out.println("Hello service unavailable on HelloConsumer stop");
		} else {
			System.out.println(hello.sayGoodbye());
		}
	}
}
